package mailx

import (
	"fmt"
	"io"
)

type writer struct {
	Len int

	sepBytes []byte
	w        io.Writer
	i        int
}

func (w *writer) Write(b []byte) (N int, err error) {
	to := w.Len - w.i

	for len(b) > to {
		var n int

		if n, err = w.w.Write(b[:to]); err != nil {
			err = fmt.Errorf("%w", err)
			return
		}

		N, b = N+n, b[to:]

		if _, err = w.w.Write(w.sepBytes); err != nil {
			err = fmt.Errorf("%w", err)
			return
		}

		w.i, to = 0, w.Len
	}

	w.i += len(b)

	var n int
	if n, err = w.w.Write(b); err != nil {
		err = fmt.Errorf("%w", err)
		return
	}
	N += n

	return
}

// NewRFC822 Creates a RFC822 text wrapper. It adds a CRLF (ie. \r\n) each 76 characters.
func NewRFC822(w io.Writer) io.Writer {
	return &writer{Len: 76, sepBytes: []byte{'\r', '\n'}, w: w}
}
